#include<iostream>
#include<unistd.h>
#include<cerrno>
#include<cstring>
#include<sys/types.h>
#include<sys/wait.h>
#include<string>
#define SIZE 1024

void ChildProcessWrite(int wid)
{
    std::string message = "Father, I am your child process. messageid->";
    int mid = 0, pid = getpid();
    size_t pipesize = 0;
    while(1)
    {
        
        // std::string tmp(message + std::to_string(++mid) + " pid->" + std::to_string(pid));
        // //字符串以'\0'结尾是C语言的要求，不是写文件的要求，实际写文件时不会把'\0'写进去：
        // write(wid, tmp.c_str(), tmp.size());
        // if(mid <= 5)
        // sleep(1);

        //测试管道大小的：
        char c = 'A';
        write(wid, &c, 1);
        std::cout << "pipesize->" << ++pipesize << std::endl;
    }
}
void FatherProcessWrite(int rid)
{
    //read函数的返回值是读到的字符个数：
    char buff[SIZE] = { 0 };
    sleep(10);
    return;
    while(1)
    {
        //空出buff数组的一个空间用来存放'\0'
        int n = read(rid, buff, sizeof(buff) - 1);
        //n > 0说明读到了数据：
        if(n > 0)
        {
            buff[n] = 0;
        }
        else break;
        std::cout << buff << std::endl;
    }
}
int main()
{
    //1.创建管道：
    int pipeid[2];       //输出项参数；
    int n = pipe(pipeid);
    if(n != 0)
    {
        std::cerr << errno << "->" << strerror(errno) << std::endl;
    }
    //pipeid[0] -> rfd; pipe[1] -> wfd:
    std::cout << "pipeid[0]->" << pipeid[0] << std::endl;
    std::cout << "pipeid[1]->" << pipeid[1] << std::endl;

    //2.创建子进程：
    pid_t id = fork();
    if(id == 0)
    {   
        //child：子进程发消息（write）
        close(pipeid[0]);
        // //测试爷孙进程彼此之间是否可以相互通信：
        // if(fork() > 0) exit(0);
        // //下面就是子进程的进程在发消息了：
        ChildProcessWrite(pipeid[1]);
        close(pipeid[1]);
        exit(0);
    }
    
    //father:父进程收消息（read）
    close(pipeid[1]);
    FatherProcessWrite(pipeid[0]);
    close(pipeid[0]);

    //3.解决子进程退出后的僵尸问题：
    int status = 0;
    pid_t wid = waitpid(id, &status, 0);
    if(wid < 0)
    {
        std::cout << "ERRNO: Can't create child process or the child's pid doesn't exist" << std::endl;
        exit(1);
    }
    else
    {
        if(WIFEXITED(status))
        {
            //tmp拿到进程的退出码部分：
            int tmp = WEXITSTATUS(status);
            printf("errno[%d]: %s\n", tmp, strerror(tmp)); 
        }
        else printf("The child process adnormally exit, exit signal: %d\n", status & 0x7f);
    }
    return 0;
}